import {changeCartGoodAPI, deleteCartGoodAPI, getShopCartListAPI} from "@/api/shopCartApi";

const actions = {
    /* 获取购物车列表的actions */
    async fetchShopCartList(context) {
        const {data} = await getShopCartListAPI()
        context.commit("updateShopCartList", data[0]?.cartInfoList || [])
    },
    /* 删除购物车某一个商品的actions */
    async deleteCartGood(context, id) {
        const result = await deleteCartGoodAPI(id)
        if (result.code !== 200) return Promise.reject("删除商品失败")
        return Promise.resolve("删除商品成功")
    },
    /* 修改购物车某一个商品状态的actions */
    async changeCartGood(context, params) {
        const result = await changeCartGoodAPI(params)
        if (result.code !== 200) return Promise.reject("修改失败")
        return Promise.resolve("修改成功")
    },
    /* 删除购物车选中商品的actions */
    async deleteCartCheckedGood(context) {
        const promiseArray = []
        context.state.shopCartList.forEach(item => {
            if (item.isChecked !== 1) return
            const promise = context.dispatch("deleteCartGood", item.skuId)
            promiseArray.push(promise)
        })
        return Promise.all(promiseArray)
    },
    /*修改购物车全部商品状态的actions*/
    async changeCartAllGood(context, isChecked) {
        const promiseArray = []
        context.state.shopCartList.forEach(item => {
            const promise = context.dispatch("changeCartGood", {skuId: item.skuId, isChecked})
            promiseArray.push(promise)
        })
        return Promise.all(promiseArray)
    }


}
const mutations = {
    /* 更新购物车列表的mutations */
    updateShopCartList(state, shopCartList) {
        state.shopCartList = shopCartList
    }
}
const state = () => {
    return {
        /* 购物车的商品列表 */
        shopCartList: []
    }
}
const getters = {
    /* 购物车的选中数量 */
    shopCartListLength: state => state.shopCartList.filter(item => item.isChecked === 1).length,
    /* 选中的总价 */
    totalPrice: state => state.shopCartList.filter(item => item.isChecked === 1).reduce((previousValue, currentValue) => previousValue += currentValue.skuNum * currentValue.skuPrice, 0),
    /* 是否全选 */
    isAllChecked: state => state.shopCartList.every(item => item.isChecked === 1)

}
export default {
    actions,
    mutations,
    state,
    getters,
    namespaced: true
}
